package com.thread.lesson.lock;

/**
 * @Author: Mr.Xi
 * @Description:
 * @Date: Create in 15:25 2021/7/5
 * @Modified By:
 */

import com.thread.lesson.demo01.TestThread2;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试Lock锁
 */
public class TeatLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();

    }

}

class TestLock2 implements Runnable{
    int ticketNum = 10;

    //定义Lock锁
    private final ReentrantLock lock  = new ReentrantLock();

    @Override
    public void run() {
        while(true){
            try {
                lock.lock();//加锁
                if (ticketNum > 0 ){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNum--);
                }else {
                    break;
                }
            }finally {
                //解锁
                lock.unlock();
            }


        }

    }
}
